/**
  Http 客户端
*/
package topgoer_http

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"reflect"
	"strings"
)

func RequestGet(urlStr string, data interface{}) {
	typeObj := reflect.TypeOf(data)
	value := reflect.ValueOf(data)
	query := url.Values{}

	for i := 0; i < typeObj.NumField(); i++ {
		query.Set(strings.ToLower(typeObj.Field(i).Name), value.Field(i).String())
	}
	uri, err := url.ParseRequestURI(urlStr)
	if err != nil {
		fmt.Printf("parse url requestUrl failed,err:%v\n", err)
	}
	// URL 编码
	uri.RawQuery = query.Encode()
	fmt.Println("当前请求是", uri.String())

	resp, http_err := http.Get(uri.String())
	if http_err != nil {
		fmt.Println("请求失败", err)
		return
	}
	//关闭响应流
	defer resp.Body.Close()

	all, err := ioutil.ReadAll(resp.Body)

	if err != nil {
		fmt.Println("get resp failed,err:%v\n", err)
		return
	}
	fmt.Println(string(all))
}

// Http get请求方法
func GetHandler(w http.ResponseWriter, req *http.Request) {
	defer req.Body.Close()
	// 获取请求参数
	query := req.URL.Query()

	for key, value := range query {
		fmt.Println("key= value=", key, value)
	}

	urlStr := req.URL.String()
	w.Write([]byte(urlStr))

}

// 路径与方法绑定
func HandleServer(path string, method interface{}) {
	methods := method.(func(w http.ResponseWriter, r *http.Request))
	http.HandleFunc(path, methods)
	err := http.ListenAndServe(":9090", nil)
	if err != nil {
		fmt.Printf("http server failed, err:%v\n", err)
		return
	}
}

// Post 请求
func PostHandle(path string, data interface{}) {

}
